// /stores/app.js
import {
	defineStore
} from 'pinia'
import http from '@/http/request' // 走你封装的拦截器

// —— 小工具：把“01：48：32”这种全角分隔时间转秒，再转回 HH:MM:SS —— //
function parseDurationToSeconds(str) {
	if (!str) return 0
	const normalized = String(str).replace(/：/g, ':').replace(/[^\d:]/g, '')
	const [hh = '0', mm = '0', ss = '0'] = normalized.split(':')
	return (+hh) * 3600 + (+mm) * 60 + (+ss)
}

function secondsToHHMMSS(total) {
	const h = Math.floor(total / 3600)
	const m = Math.floor((total % 3600) / 60)
	const s = total % 60
	const pad = (n) => String(n).padStart(2, '0')
	return `${pad(h)}:${pad(m)}:${pad(s)}`
}

function toMonthKey(dateStr) {
	const d = new Date(String(dateStr).replace(/-/g, '/'))
	const y = d.getFullYear()
	const m = String(d.getMonth() + 1).padStart(2, '0')
	return `${y}-${m}`
}

export const useAppStore = defineStore('app', {
	state: () => ({
		// —— 登录态（后面接后端再改） —— //
		isLoggedIn: false,
		token: null,
		today: {
			date: '',
			steps: 0
		},

		// —— 学生信息（示例） —— //
		student: {
			id: 'S202501',
			name: '张三',
			gender: '男',
			age: 20,
			university: '海南软件职业技术学院',
			college: '计算机与人工智能学院',
			major: '软件工程',
			className: '22级软工1班',
			phone: '188****0000',
			avatar: '/static/avatar-default.png',
			target: 9000 // ✅ 目标步数
		},

		// —— 课程信息：按需从后端拉取（默认空；进入课程页再拉） —— //
		courses: [],
		coursesLoading: false,
		coursesLoaded: false,
		lastCoursesFetchedAt: 0,

		// —— 跑步记录：按月懒加载（历史记录页用） —— //
		run: {
			recordsByMonth: {},
			loadingByMonth: {},
			loadedByMonth: {}
		}
	}),

	getters: {

		todaySteps(state) {
			return Number(state.today?.steps || 0)
		},
		// 扁平化后的所有跑步记录（按日期倒序）
		allRunRecords(state) {
			const list = Object.values(state.run.recordsByMonth).flat()
			return list.sort((a, b) => {
				const da = new Date(String(a.date).replace(/-/g, '/')).getTime()
				const db = new Date(String(b.date).replace(/-/g, '/')).getTime()
				return db - da
			})
		},

		// 跑步汇总（次数/步数/总时长）
		runSummary() {
			const list = this.allRunRecords
			const times = list.length
			const steps = list.reduce((s, r) => s + (r.steps || 0), 0)
			const totalSeconds = list.reduce((s, r) => s + parseDurationToSeconds(r.duration), 0)
			return {
				times,
				steps,
				duration: secondsToHHMMSS(totalSeconds)
			}
		},

		// 上一次跑步
		lastRun() {
			return this.allRunRecords[0] || null
		}
	},

	actions: {
		// 登录后替换数据（给你接后端用；不自动拉课程！）
		setFromServer(payload = {}) {
			if (payload.student) this.student = payload.student
			if (payload.courses) this.courses = payload.courses
			if (payload.run?.recordsByMonth) this.run.recordsByMonth = payload.run.recordsByMonth
			if (payload.token) this.token = payload.token
			if (typeof payload.isLoggedIn === 'boolean') this.isLoggedIn = payload.isLoggedIn
		},

		// 新增一条跑步记录（自动归入对应月份并按日期倒序）
		addRunRecord(rec) {
			if (!rec?.date) return
			const monthKey = toMonthKey(rec.date)
			if (!this.run.recordsByMonth[monthKey]) this.run.recordsByMonth[monthKey] = []
			this.run.recordsByMonth[monthKey].push(rec)
			this.run.recordsByMonth[monthKey].sort((a, b) => {
				const da = new Date(String(a.date).replace(/-/g, '/')).getTime()
				const db = new Date(String(b.date).replace(/-/g, '/')).getTime()
				return db - da
			})
		},

		// 清空（登出等场景）
		resetAll() {
			this.$reset()
		},
		// 主页拿到今日步数后用 set（覆盖为服务端/微信返回的真实值）
		setTodaySteps(steps, dateStr) {
			const d = dateStr || new Date().toISOString().slice(0, 10) // 'YYYY-MM-DD'
			this.today = {
				date: d,
				steps: Number(steps) || 0
			}
		},

		// 本次跑步结束后用 add（叠加增量）；若跨天则重置到当天再加
		addTodaySteps(delta, dateStr) {
			const d = dateStr || new Date().toISOString().slice(0, 10)
			if (this.today.date !== d) this.today = {
				date: d,
				steps: 0
			}
			const cur = Number(this.today.steps || 0)
			this.today.steps = Math.max(0, cur + Number(delta || 0))
		},

		// 累加课程完成步数：delta 为本次新增
		addCourseSteps({
			courseId,
			delta
		}) {
			if (!courseId) return
			const list = this.courses || []
			const i = list.findIndex(c => String(c.id) === String(courseId))
			if (i === -1) return
			const c = {
				...list[i]
			}
			const cur = Number(c.completedSteps || 0)
			const tgt = Number(c.targetSteps || 0)
			const next = cur + Number(delta || 0)
			c.completedSteps = tgt > 0 ? Math.min(next, tgt) : next // 可选：封顶到目标
			this.courses.splice(i, 1, c)
		},
		// —— 历史记录：按月从后端拉取 —— //
		async fetchRunByMonth(monthKey) {
			if (!monthKey) return
			if (this.run.loadingByMonth[monthKey]) return
			// 如果要“只拉一次”，可以放开下一行：
			// if (this.run.loadedByMonth[monthKey]) return

			this.run.loadingByMonth[monthKey] = true
			try {
				// ✅ 用 http 封装；GET 会把第二参自动拼到 query 上
				// 期望回包就是 data 本体：{ list: [...] }
				const data = await http.get('/api/run/records', {
					month: monthKey
				})

				const list = Array.isArray(data?.list) ? data.list : []
				const sorted = list.slice().sort((a, b) => {
					const da = new Date(String(a.date).replace(/-/g, '/') + ' ' + (a.time ||
						'00:00')).getTime()
					const db = new Date(String(b.date).replace(/-/g, '/') + ' ' + (b.time ||
						'00:00')).getTime()
					return db - da
				})
				this.run.recordsByMonth[monthKey] = sorted
				this.run.loadedByMonth[monthKey] = true
			} catch (e) {
				console.warn('fetchRunByMonth error', e)
				if (!this.run.recordsByMonth[monthKey]) this.run.recordsByMonth[monthKey] = []
			} finally {
				this.run.loadingByMonth[monthKey] = false
			}
		},

		// —— 课程：进入“课程页”时再拉；有 TTL 缓存；支持 force 强刷 —— //
		/**
		 * 拉取课程列表（不分学期）
		 * @param {{ force?: boolean, ttl?: number }} opts
		 *  - force: 是否强制刷新（默认 false）
		 *  - ttl: 缓存有效期，毫秒（默认 5 分钟）
		 */
		async fetchCourses(opts = {}) {
			const {
				force = false, ttl = 5 * 60 * 1000
			} = opts

			if (this.coursesLoading) return

			// TTL 缓存
			if (!force && this.coursesLoaded) {
				const notExpired = Date.now() - this.lastCoursesFetchedAt < ttl
				if (notExpired && Array.isArray(this.courses) && this.courses.length) return
			}

			this.coursesLoading = true
			try {
				// ✅ 用 http；期望回包就是 data（可能是 {list:[...]}/[...]/对象）
				const data = await http.get('/api/courses')

				// 兼容三种返回：{list:[...]}/[...]/单对象
				let list = []
				if (Array.isArray(data?.list)) list = data.list
				else if (Array.isArray(data)) list = data
				else if (data && typeof data === 'object') list = [data]

				this.courses = (list || []).map((it) => ({
					id: it.id,
					name: it.name || it.title || '课程',
					targetSteps: Number(it.targetSteps ?? it.goalSteps ?? 0),
					completedSteps: Number(it.completedSteps ?? it.progress ?? 0),
					deadline: it.deadline ?? it.deadline_date ?? '',
					credit: Number(it.credit ?? 0),
					useAutoProgress: !!it.useAutoProgress
				}))

				this.coursesLoaded = true
				this.lastCoursesFetchedAt = Date.now()
			} catch (e) {
				console.warn('fetchCourses error', e)
			} finally {
				this.coursesLoading = false
			}
		}
	},

	// ✅ 持久化
	persist: {
		storage: {
			getItem: (key) => uni.getStorageSync(key),
			setItem: (key, value) => uni.setStorageSync(key, value)
		},
		paths: [
			'student',
			'isLoggedIn',
			'token',
			'courses',
			'run.recordsByMonth',
			'today'
		]
	}
})